package com.doghome.news.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.doghome.news.annotation.CheckPermission;
import com.doghome.news.entity.News;
import com.doghome.news.service.NewsService;
import com.doghome.news.utils.BizCode;
import com.doghome.news.utils.BizDto;
import com.github.pagehelper.PageInfo;

@RestController
public class NewsController {
	
	@Autowired
	private NewsService newsService;
	
	@GetMapping("/newsByPage")
	public BizDto<PageInfo<News>> newsByPage(@RequestParam Map<String, Object> params){
		if(!params.containsKey("pageNum")|| !params.containsKey("pageSize")) {
			return new BizDto<PageInfo<News>>(BizCode.ERROR, "页码或页容量不能为空！", null);
		}
	 
		Integer tid = null;
		if(params.get("tid") != null&&params.get("tid").toString().length()>0) {
			tid = Integer.parseInt(params.get("tid").toString());
		}
		String title = params.get("title") == null ? null : "%"+params.get("title").toString()+"%";
		int pageNum = Integer.parseInt(params.get("pageNum").toString());
		int pageSize = Integer.parseInt(params.get("pageSize").toString());
		PageInfo<News> pageInfo = newsService.newsByPage(tid, title, pageNum, pageSize);
		return new BizDto<PageInfo<News>>(BizCode.SUCCESS, "成功", pageInfo);
	}
	
	@GetMapping("/showNews")
	public BizDto<News> showNews(Integer nid){
		return new BizDto<News>(BizCode.SUCCESS, "成功", newsService.showNewsById(nid));
	}
	
	@PostMapping("/addNews")
	@CheckPermission(permission = {1})
	public BizDto<Boolean> addNews(@RequestBody News news){
		BizDto<Boolean> bizDto = new BizDto<Boolean>();
		if(newsService.addNews(news)) {
			bizDto.setCode(BizCode.SUCCESS);
			bizDto.setMsg("success");
			bizDto.setData(true);
		}else {
			bizDto.setCode(BizCode.ERROR);
			bizDto.setMsg("error");
			bizDto.setData(false);
		}
		return bizDto;
	}

	@PostMapping("/editNews")
	public BizDto<Boolean> editNews(@RequestBody News news) {
		BizDto<Boolean> bizDto = new BizDto<Boolean>();
		if(newsService.editNews(news)) {
			bizDto.setCode(BizCode.SUCCESS);
			bizDto.setMsg("success");
			bizDto.setData(true);
		}else {
			bizDto.setCode(BizCode.ERROR);
			bizDto.setMsg("error");
			bizDto.setData(false);
		}
		return bizDto;
	}
	
	@GetMapping("/delNews")
	@CheckPermission(permission = {1})
	public BizDto<Boolean> delNews(int nid){
		BizDto<Boolean> bizDto = new BizDto<Boolean>();
		if(newsService.delNews(nid)) {
			bizDto.setCode(BizCode.SUCCESS);
			bizDto.setMsg("success");
			bizDto.setData(true);
		}else {
			bizDto.setCode(BizCode.ERROR);
			bizDto.setMsg("error");
			bizDto.setData(false);
		}
		return bizDto;
	}
}
